﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TemplateWeb.Models;
using TemplateWeb.Models.ViewModels;
using System.Web.Security;
using TemplateWeb.Helpers;
using TemplateWeb.DTO;

namespace TemplateWeb.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index(string infotxt = "")
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            if (!infotxt.Equals(string.Empty))
            {
                ViewData["infotxt"] = infotxt;
            }
            return View(CreateViewModel(data));
        }

        public ActionResult HuongDan()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_HUONGDAN
            };
            return View(CreateViewModel(data));
        }

        public ActionResult TimKiem()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TIMKIEM
            };
            return View(CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TimKiem(FormCollection forms)
        {
            var tieude = forms.GetValues("tieude")[0];
            var timtrongmotachitiet = bool.Parse(forms.GetValues("timtrongmotachitiet")[0]);
            var thumuc = forms.GetValues("thumuc")[0];
            var nguoiban = forms.GetValues("nguoiban")[0];
            var batdausaungay = forms.GetValues("batdausaungay")[0];
            var ketthuctruocngay = forms.GetValues("ketthuctruocngay")[0];

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TIMKIEM_SUBMITTED,
                TimKiem_TieuDe = tieude,
                TimKiem_TimTrongMoTa = timtrongmotachitiet,
                TimKiem_ThucMuc = thumuc,
                TimKiem_NguoiBan = nguoiban,
                TimKiem_BatDauSauNgay = batdausaungay,
                TimKiem_KetThucTruocNgay = ketthuctruocngay
            };
            return View("KetQuaTimKiem", CreateViewModel(data));
        }

        public ActionResult CacHangMuc()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CACHANGMUC
            };
            return View(CreateViewModel(data));
        }

        public ActionResult XemChiTietPhien(int idphien)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_XEMCHITIETPHIEN,
                IDPhienDauGia = idphien
            };
            return View(CreateViewModel(data));
        }

        public ActionResult CacPhienThanhCong()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CACPHIENTHANHCONG,
            };
            return View(CreateViewModel(data));
        }

        public ActionResult CacPhienCungNguoiDang(Guid idnguoidang)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CACPHIENCUNGNGUOIDANG,
                IDNguoiDang = idnguoidang
            };
            return View("XemCacPhienHienThoi", CreateViewModel(data));
        }

        public ActionResult CacPhienThangCuoc(Guid idnguoidung)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CACPHIENTHANGCUOC,
                IDNguoiDung = idnguoidung
            };
            return View(CreateViewModel(data));
        }

        public ActionResult DauGiaCuaToi(Guid idnguoidung)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DAUGIACUATOI,
                IDNguoiDung = idnguoidung
            };
            return View(CreateViewModel(data));
        }

        public ActionResult XemPhienDaTao(Guid idnguoidang)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_XEMPHIENDATAO,
                IDNguoiDang = idnguoidang
            };
            return View(CreateViewModel(data));
        }

        public ActionResult XemTatCaCacPhien()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_XEMTATCACACPHIEN
            };
            return View("XemCacPhienHienThoi", CreateViewModel(data));
        }

        public ActionResult XemCacPhien(int iddanhmucchinh)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_XEMCACPHIEN,
                IDDanhMucChinh = iddanhmucchinh
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ThongTinTaiKhoan(string username)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_NGUOIDUNG,
                UserName = username
            };
            return View("ThongTinTaiKhoan", CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CapNhatThongTinTaiKhoan(FormCollection forms)
        {
            var NguoiDungInfo = new EditNguoiDungViewModel
            {
                ID = Guid.Parse(forms.GetValues("idnguoidung")[0])
            };

            var extrainfo = _repNguoiDung.SelectByID(NguoiDungInfo.ID);

            extrainfo.HoTen = forms.GetValues("hoten")[0];
            extrainfo.DiaChi = forms.GetValues("diachi")[0];
            extrainfo.SoDienThoai = forms.GetValues("sodienthoai")[0];
            extrainfo.SoTaiKhoan = forms.GetValues("sotaikhoan")[0];

            // Kiem tra so tai khoan nhap vao co hop le hay khong
            var infoTxt = string.Empty;
            if (BankingService.Instance.CheckCardID(extrainfo.SoTaiKhoan))
            {
                var result = _repNguoiDung.Update(extrainfo);
                infoTxt = result ? "Đã cập nhật thông tin" : "Thông tin chưa được cập nhật";
            }
            else
            {
                infoTxt = "Ngân hàng không tìm thấy số tài khoản do bạn nhập vào, vui lòng nhập lại!";
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_NGUOIDUNG,
                GuidID = NguoiDungInfo.ID,
                InfoText = infoTxt
            };
            return View("ThongTinTaiKhoan", CreateViewModel(data));
        }

        public ActionResult TaoPhienMoi()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TAOPHIENMOI
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TaoPhienMoi(FormCollection forms)
        {
            string idhinhthucdaugia = forms.GetValues("hinhthucdaugia")[0];

            string thumuc = forms.GetValues("thumuc")[0];
            string[] thumucComps = thumuc.Split(new char[] { '-' });
            string iddanhmuccon = thumucComps[1];

            string idnguoidang = forms.GetValues("idnguoidang")[0];
            string tensanpham = forms.GetValues("tensanpham")[0];
            string xuatxu = forms.GetValues("xuatxu")[0];
            string mota = forms.GetValues("mota")[0];

            string thoigianbatdau = forms.GetValues("thoigianbatdau")[0];
            thoigianbatdau += " " + forms.GetValues("giobatdau")[0] + ":" + forms.GetValues("phutbatdau")[0] + ":00";

            string thoigianketthuc = forms.GetValues("thoigianketthuc")[0];
            thoigianketthuc += " " + forms.GetValues("gioketthuc")[0] + ":" + forms.GetValues("phutketthuc")[0] + ":00";

            var file = Request.Files["hinhanh"];

            var newItem = new PhienDauGiaDTO
            {
                IDHinhThucDauGia = int.Parse(idhinhthucdaugia),
                //IDDanhMucCon = int.Parse(iddanhmuccon),
                //IDNguoiDang = Guid.Parse(idnguoidang),
                //TenSanPham = tensanpham,
                //XuatXu = xuatxu,
                //MoTa = mota,
                //ThoiGianBatDau = thoigianbatdau == "" ? DateTime.Now : DateTime.Parse(thoigianbatdau),
                //ThoiGianKetThuc = thoigianketthuc == "" ? DateTime.Now : DateTime.Parse(thoigianketthuc),
                //KetQua = "Chờ đấu giá",
                //HinhAnh = "noimages.jpg",
                //XuatHienOTrangChu = false,
                //Duyet = true
            };

            if (_repHinhThucDauGia.SelectByID(newItem.IDHinhThucDauGia).TenHinhThucDauGia.ToUpper().Contains("ANH"))
            {
                newItem.GiaKhoiDiem = long.Parse(forms.GetValues("giakhoidiem")[0].Replace(".", string.Empty).Replace(",", string.Empty));
            }
            else
            {
                newItem.GiaToiThieu = long.Parse(forms.GetValues("giatoithieu")[0].Replace(".", string.Empty).Replace(",", string.Empty));
                newItem.TienDatCoc = long.Parse(forms.GetValues("tiendatcoc")[0].Replace(".", string.Empty).Replace(",", string.Empty));
            }

            var result = _repPhienDauGia.Insert(newItem);
            string refName = string.Empty;

            if (result)
            {
                if (file != null && file.ContentLength != 0)
                {
                    result = UploadFile(file, "/Content/Images/Items/", ref refName);
                    if (result)
                    {
                        var addedItem = _repPhienDauGia.SelectByID(newItem.ID);
                        //addedItem.HinhAnh = refName;
                        _repPhienDauGia.Update(addedItem);
                    }
                }
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TAOPHIENMOI_SUBMITTED,
                InfoText = result ? "Tạo phiên thành công." : "Không thể tạo phiên mới."
            };

            return View("TaoPhienMoi", CreateViewModel(data));
        }

        public ActionResult XemCacPhienTheoHangMuc(int iddanhmucchinh, int iddanhmuccon = -1)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_XEMCACPHIENTHEOHANGMUC,
                IDDanhMucChinh = iddanhmucchinh,
                IDDanhMucCon = iddanhmuccon
            };
            return View(CreateViewModel(data));
        }

        public ActionResult DatChoDauGia(int idphiendaugia)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DATCHODAUGIA,
                IDPhienDauGia = idphiendaugia
            };
            var model = CreateViewModel(data);
            if (model.PhienDauGiaModel.GetModel.LstObjModel[0].HinhThucDauGia.TenHinhThucDauGia.ToUpper().Contains("ANH"))
            {
                return View(model);
            }
            return View("DatChoDauGiaNguoc", model);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DatChoDauGia(FormCollection forms)
        {
            string giaduara = forms.GetValues("giaduara")[0].Replace(".", string.Empty).Replace(",", string.Empty);
            string idnguoidung = forms.GetValues("idnguoidung")[0];
            string idphiendaugia = forms.GetValues("idphiendaugia")[0];

            var nguoidung = _repNguoiDung.SelectByID(Guid.Parse(idnguoidung));
            var phiendaugia = _repPhienDauGia.SelectByID(int.Parse(idphiendaugia));

            var isPermission = true;
            var infoTxt = string.Empty;
            var auctionSuccess = false;

            // Hinh thuc dau gia nguoc
            if (!phiendaugia.HinhThucDauGia.TenHinhThucDauGia.ToUpper().Contains("ANH"))
            {
                var sotiencoc = phiendaugia.TienDatCoc;
                // Lay so tien con lai trong tai khoan
                var balance = BankingService.Instance.GetBalance(nguoidung.SoTaiKhoan);

                // Khong du tien trong tai khoan de tham gia dau gia
                if (balance < sotiencoc)
                {
                    isPermission = false;
                    infoTxt = "Bạn không đủ tiền trong tài khoản để tham gia đấu giá";
                }
            }

            // Nguoi dung duoc phep dau gia
            if (isPermission)
            {
                var newItem = new NguoiChoiDauGiaDTO
                {
                    IDNguoiDung = Guid.Parse(idnguoidung),
                    IDPhienDauGia = int.Parse(idphiendaugia),
                    ThoiDiemDauGia = DateTime.Now,
                    GiaDuaRa = long.Parse(giaduara)
                };
                auctionSuccess = _repNguoiChoiDauGia.Insert(newItem);
                infoTxt = auctionSuccess ? "Đấu giá thành công" : "Đấu giá thất bại";

                // Dau gia thanh cong, tru tien coc trong tai khoan
                if (auctionSuccess && !phiendaugia.HinhThucDauGia.TenHinhThucDauGia.ToUpper().Contains("ANH"))
                {
                    // Gia dinh tai khoan cua cong ty so huu trang web dau gia la "111222333"
                    BankingService.Instance.ExChangeVND(nguoidung.SoTaiKhoan, "123", "111222333", (decimal)phiendaugia.TienDatCoc);
                }
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DATCHODAUGIA,
                IDPhienDauGia = int.Parse(idphiendaugia),
                InfoText = infoTxt
            };

            var model = CreateViewModel(data);
            if (model.PhienDauGiaModel.GetModel.LstObjModel[0].HinhThucDauGia.TenHinhThucDauGia.ToUpper().Contains("ANH"))
            {
                return View(model);
            }
            return View("DatChoDauGiaNguoc", model);
        }

        public ActionResult GopY()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertHopThu(FormCollection forms)
        {
            string hoten = forms.GetValues("HopThu_HoTen")[0];
            string email = forms.GetValues("HopThu_Email")[0];
            string tieude = forms.GetValues("HopThu_TieuDe")[0];
            string noidung = forms.GetValues("HopThu_NoiDung")[0];

            var newItem = new HopThuDTO
            {
                EmailNguoiHoi = email,
                TieuDe = tieude,
                NoiDung = noidung,
                NgayHoi = DateTime.Now,
                DaPhanHoi = false,
                HoTen = hoten
            };
            var result = _repHopThu.Insert(newItem);
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            ViewData["HoiDap"] = result ? "Thư của bạn đã được gửi đi, sau khi xem xét chúng tôi sẽ gửi phản hồi cho bạn!" : "Thư của bạn chưa được gửi đi, có lỗi sảy ra trong quá trình gửi câu hỏi.";
            return View("GopY", CreateViewModel(data));
        }
    }
}
